/*
 * Copyright (C) 2000-2007 Wang Pengcheng <wpc0000@gmail.com>
 * Licensed to the Wang Pengcheng under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The LGPL licenses this file to You under the GNU Lesser General Public
 * Licence, Version 2.0  (the "License"); you may not use this file except in
 * compliance with the License.  You may obtain a copy of the License at
 *
 *     http://www.gnu.org/licenses/lgpl.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//29 Aug 2007
package cn.edu.whu.control;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import cn.edu.whu.data.DataList;
import cn.edu.whu.data.VarList;

/**
 * Edit the SQLMapConfig.xml file
 * @author wpc
 * @version 0.0.1
 * 
 */
public class EditConfigXml {
	
	private static String fileUrl = BasicDataForEdit.TEMPLATE_FILE_DIR+"databaseAction/SQLMapConfig.xml";

	private static String SALE_FILE_NAME="test.xml";
	
	private VarList var;

	private DataList list;
	
	private String file="";
	
	public EditConfigXml(VarList var,DataList list){
		this.var=var;
		this.list=list;
		
	}
	
	public void read(String fileUrl) throws Exception{
		this.fileUrl=fileUrl;
		read();
	}
	
	public void read() throws Exception{
		
		//InputStream storageFile = getClass().getResourceAsStream(fileUrl);

		
		FileInputStream storageFile = new FileInputStream(fileUrl);
		BufferedReader in = new BufferedReader(new InputStreamReader(
				storageFile));
		
		while(true){
			String s = in.readLine();
			if(s==null){
				break;
			}
			file+=s+"\n";
		}
	}
	
	public void change(){
		for(int i=0;i<var.length();i++){
			file=file.replace(var.getVar(i), var.getValue(i));
		}
	}
	
	public void write() throws Exception{
		FileOutputStream saleFile = new FileOutputStream(SALE_FILE_NAME);
		BufferedWriter out = new BufferedWriter(
				new OutputStreamWriter(saleFile));
		out.flush();
		out.newLine();
		out.append(file);
		out.close();
	}
	
	public String toString(){
		return file;
	}
	
	public void setPath(String url){
		SALE_FILE_NAME=url;
	}
}
